package com.homelock.service;

import java.util.List;
import java.util.stream.Collectors;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.alibaba.dubbo.common.utils.CollectionUtils;
import com.homelock.entity.HlDevInfo;
import com.homelock.entity.HlDevUser;
import com.homelock.service.check.RemoteUnlockCheckUtil;
import com.pi.base.enumerate.redis.RedisCacheEnum;
import com.pi.base.exception.ServiceException;
import com.pi.base.util.cache.RedisUtil;
import com.pi.uc.dao.entity.UcUserEntity;
import com.pi.uc.service.UcUserService;

@Service
public class RemoteUnlockService {

    private static final Logger logger = LoggerFactory.getLogger(RemoteUnlockService.class);

    private UcUserService userService;

    private HlDevInfoService devInfoService;

    private LockUserService lockUserService;

    @Autowired
    public RemoteUnlockService(UcUserService userService, HlDevInfoService devInfoService,
            LockUserService lockUserService) {
        this.userService = userService;
        this.devInfoService = devInfoService;
        this.lockUserService = lockUserService;
    }

    public void remoteUnlock(Long devId, Long userId) {
        RemoteUnlockCheckUtil.checkRemoteUnlock(devId, userId);
        logger.info("[remote_unlock] devId:{}, userId: {}", devId, userId);
        HlDevInfo devInfo = devInfoService.getDevInfobyId(devId);
        if (null == devInfo) {
            throw new ServiceException("DEV_INFO_EMPTY");
        }
        UcUserEntity userInfo = userService.queryUserInfo(userId);
        if (null == userInfo) {
            throw new ServiceException("USER_NOT_EXIST");
        }
        List<HlDevUser> lockUserList = lockUserService.queryAnyLockUserByDevId(devId);
        if (CollectionUtils.isEmpty(lockUserList)) {
            throw new ServiceException("LOCK_USER_NOT_EXIST");
        }
        List<Long> collect = lockUserList.stream().filter(o -> null != o.getUserId() && o.getUserId() > 0)
                .map(HlDevUser::getUserId).collect(Collectors.toList());
        logger.info("[remote_unlock][available_unlock_user] cloud userId:{}, current user: {}", collect, userId);
        if (CollectionUtils.isEmpty(collect) || !collect.contains(userId)) {
            throw new ServiceException("LOCK_USER_NOT_EXIST");
        }
        RedisUtil.directset(RedisCacheEnum.SMART_LOCK_REMOTE_UNLOCK, String.valueOf(System.currentTimeMillis()),
                devInfo.getDevCode().toUpperCase());
        logger.info("[remote_unlock] sended, devId:{}, userId: {}", devId, userId);
    }
}
